<!--
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2020-11-10 12:10:01
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-04-19 17:01:15
 * @Description: file content
-->
<template>
  <div class="json-editor">
    <textarea ref="textarea" />
  </div>
</template>

<script>
import CodeMirror from "codemirror";
import "codemirror/addon/lint/lint.css";
import "codemirror/lib/codemirror.css";
// import "codemirror/theme/rubyblue.css";
// 自定义base16-light主题颜色。
import "./base16-light.css";
require("script-loader!jsonlint");
import "codemirror/mode/javascript/javascript";
import "codemirror/addon/lint/lint";
import "codemirror/addon/lint/json-lint";

export default {
  name: "JsonEditor",
  /* eslint-disable vue/require-prop-types */
  props: {
    value: "",
    height: {
      type: String,
      default: "300px",
    },
    type: {
      type: String,
      default: "json",
    },
  },
  data() {
    return {
      jsonEditor: false,
      type_mode: {
        json: "application/json",
        mysql: "text/x-mysql",
        html: "text/html",
        js: "application/javascript",
      },
    };
  },
  watch: {
    value(value) {
      this.setValue(value);
    },
  },
  mounted() {
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      lineNumbers: true,
      // mode: "application/json",
      mode: this.type_mode[this.type] || "application/json",
      gutters: ["CodeMirror-lint-markers"],
      // theme: "rubyblue",
      theme: "base16-light",
      lint: true,
    });

    // this.jsonEditor.setValue(JSON.stringify(this.value, null, 4));
    this.setValue(this.value);
    this.jsonEditor.on("change", (cm) => {
      this.$emit("change", cm.getValue());
      this.$emit("input", cm.getValue());
    });
  },
  methods: {
    getValue() {
      const val = this.jsonEditor.getValue();
      return JSON.stringify(JSON.parse(val));
    },
    setValue(value) {
      // debugger
      const editorValue = this.jsonEditor.getValue();
      if (value !== editorValue) {
        let setV;
        try {
          const json = JSON.parse(value);
          setV = JSON.stringify(json, null, 4);
        } catch (error) {
          setV = value;
        }

        this.jsonEditor.setValue(setV);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.json-editor {
  height: 300px;
  overflow-y: scroll;
  overflow-x: hidden;
  position: relative;

  ::v-deep {
    .CodeMirror {
      height: auto;
      min-height: 300px;
    }

    .CodeMirror-scroll {
      min-height: 300px;
    }

    .cm-s-rubyblue span.cm-string {
      color: #f08047;
    }
  }
}
</style>
